<template>
  <span>
    <el-button
      size="small"
      type="primary"
      icon="el-icon-plus"
      @click="handleAdd()"
      >已有算法模型库包装图修改</el-button
    >

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogOpen"
      :close-on-click-modal="false"
      @close="closeDialog"
      width="800px"
      append-to-body
    >
      <el-form
        ref="algoForm"
        :model="algoForm"
        :rules="algoFormRule"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户" prop="userId">
              <el-select v-model="algoForm.userId" filterable placeholder="请选择">
                <el-option
                  v-for="item in initCustomer"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <!-- <el-input v-model="form.userId" placeholder="请输入" /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="算法sku" prop="skuId">
              <el-select
                v-model="algoForm.skuId"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in skuLibData"
                  :key="index"
                  :label="item.skuName"
                  :value="item.skuId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="算法新包装图片" prop="file">
              <input type="file" ref="alogImg" accept="image/*" @change="handFileChange" />
              <img style="width: 100px" :src="imageUrl" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelContainer">取 消</el-button>
        <el-button type="primary" @click="submitContainer">确 定</el-button>
      </div>
    </el-dialog>
  </span>
</template>

<script>
import { skuUploadPackage, getSKULibList, skuCreateV2 } from '@/api/sku/sku'
export default {
  props: ['initCustomer'],
  data() {
    return {
      dialogTitle: '修改算法模型库包装图',
      algoFormRule: {
        skuId: [{ required: true, message: '请选择', trigger: 'blur' }],
        userId: [{ required: true, message: '请选择', trigger: 'blur' }],
        file: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      algoForm: {},
      dialogOpen: false,
      skuLibData: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传的图片服务器地址
      headers: {
        // Authorization: "Bearer " + getToken()
      },
      imageUrl: '',
    }
  },
  created() {
    this.getInitData()
  },
  methods: {
    cancelContainer() {
      this.dialogOpen = false
    },
    submitContainer() {
      this.$refs.algoForm.validate((valid) => {
        if (!valid) {
          return
        }
        const form = this.algoForm
        const item = this.skuLibData.find((item) => (item.skuId = form.skuId))
        if (item) {
          let str = `&userId=${form.userId}`
          const formData = new FormData()
          Object.keys(item).forEach((key) => {
            str += `&${key}=${item[key]}`
          })
          console.log('## str ==> ', str)
          formData.append('file', this.algoForm.file)
          const params = {
            // ...item,
            url: str,
            file: formData,
            // ...form
          }
          console.log('## formdata ==> ', params)
        //   skuUploadPackage(params)
          skuCreateV2(params)
            .then((res) => {
              console.log('## res => ', res)
              this.$message.success('操作成功')
              // todos 把弹窗给关了
              this.dialogOpen = false
            })
            .catch((err) => {
              this.$message.error(err.message)
              console.log('## err ==> ', err)
            })
        } else {
          console.log('## 没有找到对应id ')
        }
      })
    },
    handFileChange(e) {
      let fileData = e.target.files[0] //这是我们上传的文件
      console.log('@@ ee => ', fileData)
      this.algoForm.file = fileData
      let reader = new FileReader()

      let url = URL.createObjectURL(fileData)
      this.imageUrl = url
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件大小
      //   if (this.fileSize) {
      //     const isLt = file.size / 1024 / 1024 < this.fileSize
      //     if (!isLt) {
      //       this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`)
      //       return false
      //     }
      //   }
      console.log('## upload filte ==> ', file)
      return false
    },
    getInitData() {
      const params = {
        pageIndex: 0,
        pageSize: 100,
      }
      getSKULibList(params)
        .then((res) => {
          console.log('## getSKULibList ==> ', res)
          this.skuLibData = res.data.data
        })
        .catch((err) => {
          console.log('## getSKULibList ==> ', err)
        })
    },
    handleAdd() {
      this.dialogOpen = true
    },
    closeDialog() {
      this.dialogOpen = false
    },
  },
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>